package net.udp.client;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

import org.apache.log4j.Logger;

import core.Props;

import net.udp.UDPProps;
import net.udp.server.UDPServer;

public class UDPClient {

	private String host;
	private Integer port;
	private InetAddress server;
	private Props props;
	private DatagramSocket socket = null;
	private static Logger logger = Logger.getLogger(UDPClient.class);
	public UDPClient()
	{		
		props = UDPProps.getInstance();		
	
		host=props.getString("server.host");
		port=props.getInt("server.port");
		
		try{
			server = InetAddress.getByName(host);		
			socket = new DatagramSocket();			
		}catch(Exception e)
		{
			e.printStackTrace();
		}
	}
	
	public String request(String request)
	{
		String output = null;
		try {
			socket.connect(server,port);
			byte[]data = request.getBytes();
			
			//send 
			DatagramPacket dp  = new DatagramPacket(data, data.length, server, port); 					
			socket.send(dp);
			logger.debug(">>\t"+request);
					
			//rececive
			
			socket.receive(dp);
			output = new String(dp.getData());
			logger.debug("<<\t"+output);
			
		} catch (Exception e) {					
			e.printStackTrace();
		}
		return output;
	}
	
	public void close()
	{
		socket.close();
	}
	
	@Override
	protected void finalize() throws Throwable {
		socket.close();
	}


}
